﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Nova_DAL;
using System.Data.Common;
using Nova_Common;
using System.Drawing;

public partial class DelStorage_SearchStock : System.Web.UI.Page
{
    Nova_DAL.DbHelper access = new DbHelper();
    string strSQL = "";
    DbCommand cmd = null;
    DataSet ds = null;
    string strMatCode = "";
    string TS01 = string.Empty;
    string delPID = "";  //出库单的PID
    string billMatCount = ""; //单据需要出库的数量

    //用于双伸位前后货位的标记
    string FrontPos_ID = "";//用于标记上一行的货位号
    Color Samecolor = Color.AliceBlue;//两个切换的颜色
    Color Diffcolor = Color.LightSkyBlue;

    ////20210426 NF项目双伸位巷道集合  需要结合项目双伸位巷道修改
    string ExtensionLanes = "(1)";
    string[] ExtensionLanelists = new string[] { "1" };
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            strMatCode = Request["strMatCode"].ToString();
            billMatCount = Request["billMatCount"].ToString();
            TS01 = Request["TS01"].ToString();
            delPID = Request["delPID"].ToString();
            string sqlStr = string.Format("SELECT PID,Mat_Code,Num,Act_Num,TS01 FROM dbo.TDelStorage_List WHERE PID={0}", delPID);
            DbCommand cmd = access.GetSqlStringCommond(sqlStr);
            DataTable dt = access.ExecuteDataTable(cmd);
            if (dt.Rows.Count > 0)
            {
                decimal num = decimal.Parse(dt.Rows[0]["Num"].ToString()) - decimal.Parse(dt.Rows[0]["Act_Num"].ToString());
                DelStorageCount.Text = num.ToString();
            }

        }
        catch
        {

        }
        if (!IsPostBack)
        {
            gvbind();
        }
    }

    /// <summary>
    /// 20200702 JFF项目
    /// 获取某种物料的所有库存明细（双伸位巷道（1#）中前面货位状态为入库预定或者移库预定的 后面货位的库存除外），按照货位（保证前后货位的相邻）、组盘时间排序
    /// 20210426 NF项目 逻辑不变 后期项目需要更改双伸位巷道号集合
    /// </summary>
    /// <returns></returns>
    protected string getSQL()
    {
        strSQL = @"Select TRP.Tray_ID,TBZ.Zone_Name,TBP.Pos_ID,TBP.No_Lane,TBM.Mat_Code,TBM.Mat_Name,
        TBS.Mat_Num,TBS.PID,TBM.Unit_Base,TBM.TM01,TBM.S01,TBM.TM03,TBM.S02,TBI.TS01,TBP.Pos_State,TBS.CDT
        From TBase_Storage TBS
        LEFT JOIN TRel_TrayPosContainer TRT ON TBS.ContainerID = TRT.ContainerID
        LEFT JOIN TBase_TrayPos TBT ON TBT.Relations_ID = TRT.Relations_ID
        LEFT JOIN TRelations TRP ON TRP.Tray_ID = TBT.Tray_ID
        LEFT JOIN TBase_Position TBP ON TRP.Pos_ID = TBP.Pos_ID
        LEFT JOIN TBase_Zone TBZ ON TBZ.Zone_ID = TBP.Zone_ID
        LEFT JOIN TBase_InterFace TBI ON TBI.Sec_Mat_ID = TBS.Sec_Mat_ID
        LEFT JOIN TBase_Material TBM ON TBM.Mat_Code = TBI.Mat_Code
        Where TRP.Pos_ID !='200000000000' and TBP.Pos_State IN(1,4) and TBP.Pos_ID is not null ";
        if (!string.IsNullOrEmpty(TS01))
        {
            strSQL += string.Format(" and (TBM.Mat_Code = '{0}' AND TBI.TS01='{1}') OR (TBM.Mat_Code = '{0}' AND TBI.TS01='')", strMatCode.ToString(), TS01);
        }
        else
        {
            strSQL += string.Format(" and TBM.Mat_Code = '{0}' and TBI.TS01=''", strMatCode.ToString());
        }
        strSQL += " order by CONVERT(varchar(10), TBS.CDT,20) ASC,TBS.Mat_Num DESC";
        return strSQL;
    }

    protected void gvbind()
    {
        cmd = access.GetSqlStringCommond(getSQL());
        gv.DataSource = access.ExecuteDataSet(cmd);
        gv.DataBind();
    }

    /// <summary>
    /// 双伸位前后货位关系 的显示同意颜色区分
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //DataRowView dr = (DataRowView)e.Row.DataItem;
                //CheckBox cbx = (CheckBox)e.Row.FindControl("chkSelect");

                Label labPos_ID = (Label)e.Row.FindControl("labPos_ID");
                Label lblNo_Lane = (Label)e.Row.FindControl("lblNo_Lane");//巷道
                Label lblPos_State = (Label)e.Row.FindControl("lblPos_State"); // 托盘在货位的状态

                //双伸位 后面货位（偶数层） 与前一行数据货位为前后关系  显示同样颜色， 否则显示不同颜色
                //if ((Convert.ToInt32(labPos_ID.Text.Substring(8, 2)) % 2) == 0 && ExtensionLanelists.Contains(lblNo_Lane.Text.Trim()) && ((Convert.ToInt64(labPos_ID.Text.Substring(0, 10)) - 1) * 100)._ToString() == FrontPos_ID)
                //{
                //    e.Row.BackColor = Samecolor;

                //}
                //else
                //{
                //    e.Row.BackColor = Diffcolor;

                //    Color Middlecolor = Samecolor;
                //    Samecolor = Diffcolor;
                //    Diffcolor = Middlecolor;

                //}
                if (lblPos_State.Text != "1")
                {
                    e.Row.ForeColor = Color.Red;
                }


                FrontPos_ID = labPos_ID.Text._ToString();
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());


        }
    }

    /// <summary>
    /// 选中按钮
    /// xgw 20210426 add  NF项目 增加双伸位 后面的货位（偶数层）添加能否出库的业务逻辑判断，不满足条件提示，跳出
    /// 如果前面的货位状态为：入库、移库预定，此货位的货物不能出库
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ibtnQuery_Click(object sender, ImageClickEventArgs e)
    {
        string strPID = "";

        for (int i = 0; i < gv.Rows.Count; i++)
        {
            CheckBox chkSelect = (CheckBox)gv.Rows[i].Cells[0].FindControl("chkSelect");
            //Label lblPID = (Label)gv.Rows[i].FindControl("lblPID");  //组盘的PID
            //Label lblMat_Num = (Label)gv.Rows[i].FindControl("lblMat_Num");//物料号
            //Label lblNum = (Label)gv.Rows[i].FindControl("lblNum");//库存数据
            Label label_PID = (Label)this.gv.Rows[i].FindControl("lblPID");  //组盘表主键PID
            Label label_Num = (Label)this.gv.Rows[i].FindControl("lblNum");//应发数量0 
            Label label_Mat_Num = (Label)this.gv.Rows[i].FindControl("lblMat_Num");//库存数量
            Label labTray_ID = (Label)this.gv.Rows[i].FindControl("labTray_ID");//托盘号

            Label labPos_ID = (Label)this.gv.Rows[i].FindControl("labPos_ID");//货位号
            Label lblNo_Lane = (Label)this.gv.Rows[i].FindControl("lblNo_Lane");//巷道
            Label lblPos_State = (Label)this.gv.Rows[i].FindControl("lblPos_State");// 托盘货位状态

            if (chkSelect.Checked)
            {
                #region xgw 20200702 add  双伸位巷道 后面的货位（偶数层）添加能否出库的业务逻辑判断，不满足条件提示，跳出
                //if ((Convert.ToInt32(labPos_ID.Text.Substring(8, 2)) % 2) == 0  && Convert.ToInt32(lblNo_Lane.Text)==2 )
                //{
                //    bool NocheckPos_State = false;   //后面的货和相邻前面货 都选中了，不用核对 前面货位的状态
                //    //1、前面的货位有货状态，但是没有选择出库，跳出;选择了，不用再核对货位的状态了！
                //    if (i > 0)
                //    {
                //        //前一行的数据(排序必须按照货位号升序)
                //        CheckBox chkSelect1 = (CheckBox)gv.Rows[i - 1].Cells[0].FindControl("chkSelect");
                //        Label labPos_ID1 = (Label)this.gv.Rows[i - 1].FindControl("labPos_ID");
                //        if ((Convert.ToInt64(labPos_ID.Text.Substring(0, 10)) - 1) * 100 == Convert.ToInt64(labPos_ID1.Text))
                //        {
                //            if (!chkSelect1.Checked)
                //            {
                //                ShowBox.MessageBox(this.Page, labPos_ID.Text + "前面的货位没有选择，此货位的货物不能出库！");
                //                return;
                //            }

                //            if (chkSelect1.Checked)
                //            {
                //                NocheckPos_State = true;
                //            }

                //        }

                //    }


                //    //2、前面的货不是选中， 核对前面货位状态， 前面货位是入、移库预定或者是有货状态，跳出
                //    if (NocheckPos_State == false)
                //    {
                //        long Pos_ID_Front = (Convert.ToInt64(labPos_ID.Text.Substring(0, 10)) - 1) * 100;
                //        string str = string.Format(@"select * from  dbo.TBase_Position where Pos_ID={0}
                //         ", Pos_ID_Front);

                //        cmd = access.GetSqlStringCommond(str);
                //        ds = access.ExecuteDataSet(cmd);
                //        if (ds.Tables[0].Rows.Count > 0)
                //        {
                //            if (Convert.ToInt16(ds.Tables[0].Rows[0]["Pos_State"]) == 2  || Convert.ToInt16(ds.Tables[0].Rows[0]["Pos_State"]) == 1 || Convert.ToInt16(ds.Tables[0].Rows[0]["Pos_State"]) == 6)
                //            {
                //                ShowBox.MessageBox(this.Page, labPos_ID.Text + "前面的货位有入、移库预定或者有货，此货位的货物不能出库！");
                //                return;
                //            }
                //        }
                //    }
                //}

                #endregion

                #region xgw 20210426 add  NF项目双伸位巷道 后面的货位（偶数层）添加能否出库的业务逻辑判断，不满足条件提示，跳出
                //如果前面的货位状态为：入库、移库预定，此货位的货物不能出库
                //if ((Convert.ToInt32(labPos_ID.Text.Substring(8, 2)) % 2) == 0 && ExtensionLanelists.Contains(lblNo_Lane.Text.Trim()))
                //{
                //    //核对前面货位状态， 前面货位是入、移库预定 跳出
                //    long Pos_ID_Front = (Convert.ToInt64(labPos_ID.Text.Substring(0, 10)) - 1) * 100;
                //    string str = string.Format(@"select * from  TBase_Position where Pos_ID={0}
                //         ", Pos_ID_Front);

                //    cmd = access.GetSqlStringCommond(str);
                //    ds = access.ExecuteDataSet(cmd);
                //    if (ds.Tables[0].Rows.Count > 0)
                //    {
                //        if (Convert.ToInt16(ds.Tables[0].Rows[0]["Pos_State"]) == 2 || Convert.ToInt16(ds.Tables[0].Rows[0]["Pos_State"]) == 6)
                //        {
                //            ShowBox.MessageBox(this.Page, labPos_ID.Text + "前面的货位有入、移库预定，此货位的货物不能出库！");
                //            return;
                //        }
                //    }

                //}

                #endregion

                if (int.Parse(lblPos_State.Text) == (int)PosStateEnum.Choose)
                {
                    ShowBox.MessageBox(this.Page, "此托盘已经生成出库指令，需等指令完成后才能再次选择此托盘出库!");
                    return;
                }



                //strPID += lblPID.Text + "|" + lblMat_Num.Text + "|" + delPID + "|"+lblNum.Text+" ,";
                strPID += label_PID.Text + "|" + 0 + "|" + this.delPID + "|" + label_Mat_Num.Text + "|" + labTray_ID.Text + "|" + labPos_ID.Text + "|" + billMatCount + ",";

            }
        }

        if (strPID.Length > 0)
        {
            strPID = strPID.ToString().TrimEnd(',');
            //this.Page.ClientScript.RegisterStartupScript(typeof(string), "Nova", "window.returnValue='" + strPID + "';top.close();", true);
            this.Page.ClientScript.RegisterStartupScript(typeof(string), "Nova1", "window.opener.document.getElementById('hidden').value='" + strPID + "';window.opener.document.getElementById('form1').submit();top.close();", true);
            return;
        }

    }

    //protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    //{
    //    if (e.Row.RowType == DataControlRowType.DataRow)
    //    {
    //        DataRowView dr = (DataRowView)e.Row.DataItem;
    //        CheckBox cbx = (CheckBox)e.Row.FindControl("chkSelect");
    //        //if (Convert.ToInt16(dr["Structure"]) != 1)
    //        //{
    //        //    cbx.Visible = false;
    //        //}
    //        //else
    //        //{
    //        //    cbx.Visible = true;
    //        //}
    //    }
    //}
}
